﻿using CommunityToolkit.Mvvm.ComponentModel;
using S7CommPlusDriver;
using S7CommPlusDriver.ClientApi;
using S7CommPlusDriverCore.Extension;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;

namespace TestS7Conm
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            S7CommPlusConnection s7CommPlusConnection = new S7CommPlusConnection();

            TagsManager tagsManager = new TagsManager();

            MainWindowViewModel mainWindowViewModel = new MainWindowViewModel(tagsManager);

            CancellationTokenSource cts = new CancellationTokenSource();
          

            StateMachineManager stateMachineManager = new StateMachineManager(s7CommPlusConnection, "192.168.0.1", 1000, cts);

            stateMachineManager.Start();

            stateMachineManager.AddInstance(mainWindowViewModel);

            DataContext = mainWindowViewModel;
            mainWindowViewModel.Write(nameof(mainWindowViewModel.B1), true);
            App.Completion.ContinueWith((t) =>
            {
                cts?.Cancel();
                stateMachineManager.Stop();
            });
        }
    }

    public partial class MainWindowViewModel : ObservableObject, ITagAware
    {
        public MainWindowViewModel(TagsManager tagsManager)
        {
            TagsManager = tagsManager;
        }

        private bool b1;

        [MonitoredItem("DB_Binary.Bool_False")]
        public bool B1
        {
            get { return b1; }
            set { SetProperty(ref b1, value); }
        }

        private bool b2;

        [MonitoredItem("DB_Binary.Bool_True")]
        public bool B2
        {
            get { return b2; }
            set { SetProperty(ref b2, value); }
        }

        public TagsManager TagsManager { get; set; }

        public void Write<T>(string name, T value)
        {
            var monitoredItemAttribute = this.GetType().GetProperty(name).GetCustomAttribute<MonitoredItemAttribute>();

            var plcTag = TagsManager.TempPlcTags.FirstOrDefault(x => x.Name == monitoredItemAttribute.TagName);

            var tempTag = Helper.CreatePlcTag(plcTag.Name, plcTag.Address, plcTag.Datatype);

            tempTag.SetValue(value);

            TagsManager.WritePlcTags.Add(tempTag);
        }
    }
}
